﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices; //调用WINDOWS API函数时要用到 
using Microsoft.Win32; //写入注册表时要用到
using MyOCR.Translate;
using System.Threading;
using MyOCR.Picture;
using System.Speech.Synthesis;

namespace MyOCR
{
    public partial class Form1 : Form
    {
        HookHandel hook = new HookHandel();//钩子
        public Action<Image> OCR_action;
        private SpeechSynthesizer speech;//语音
        public Form1()
        {
            hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);
            hook.HookStart();
            InitializeComponent();

            speech = new SpeechSynthesizer();
            speech.SelectVoice("Microsoft Huihui Desktop");
            speech.Volume = 100;//音量

            //InterfaceComboBox_1.ComboBox.DataBindings.Add("SelectedItem", Program._config, "_Recongnition");
            //LanguageComboBox.ComboBox.DataBindings.Add("SelectedItem", Program._config, "_Language");
            InterfaceComboBox_2.ComboBox.DataBindings.Add("SelectedItem", Program._config, "_Translate");

            OCR_action += Transfer;
        }

        public void setTextBox(string msg)
        {
            richTextBox1.Text = msg;
            //notifyIcon1_MouseDoubleClick(null, null);
        }

        #region MiniForm
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //是否取消close操作
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            }

            //hook.HookStop();
            //e.Cancel = true;
        }

        /// <summary>
        /// 双击图标显示窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.ShowInTaskbar = true;
        }
        #endregion

        #region ICO_Menu

        private void show_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.Show();
        }

        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
            Application.Exit();
        }
        private void setUp_Click(object sender, EventArgs e)
        {
            new SetUp().Show();
        }
        #endregion

        #region Hook
        private void hook_KeyDown(object sender, KeyEventArgs e)
        { 
            if (e.KeyValue == (int)Keys.F4)
            {
                this.Hide();

                Image img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
                Graphics g = Graphics.FromImage(img);
                g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size);

                ShowImage body = new ShowImage();
                body.BackgroundImage = img;
                body.Show(this);
            }
        }
        #endregion

        //翻译
        private void TranslateButton_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = false;
            this.Width = 800;
            splitContainer1.SplitterDistance = this.Width/2;

            if(!string.IsNullOrWhiteSpace(richTextBox1.Text))
            {
                richTextBox2.Text = "正在翻译";
                var translate = TranslateFactory.createPicture(Program._config._Translate);
                translate.need_Tslt = richTextBox1.Text;

                this.BeginInvoke(new Action(() => { richTextBox2.Text = translate.GetResult(); }));
            }
            else
            {
                return;
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = true;
            this.Width = 400;
        }

        //加粗
        private void BoldButton_Click(object sender, EventArgs e)
        {
            if (((ToolStripButton)sender).Name == "BoldButton_1")
                if (!richTextBox1.Font.Bold)
                    richTextBox1.Font = new Font(richTextBox1.Font, richTextBox1.Font.Style | FontStyle.Bold);
                else
                    richTextBox1.Font = new Font(richTextBox1.Font, FontStyle.Regular);
            else if (((ToolStripButton)sender).Name == "BoldButton_2")
                if (!richTextBox2.Font.Bold)
                    richTextBox2.Font = new Font(richTextBox2.Font, richTextBox2.Font.Style | FontStyle.Bold);
                else
                    richTextBox2.Font = new Font(richTextBox2.Font, FontStyle.Regular);
        }

        //复制
        private void CopyButton_Click(object sender, EventArgs e)
        {
            if (((ToolStripButton)sender).Name == "CopyButton_1")
                Clipboard.SetText(richTextBox1.Text);
            else if (((ToolStripButton)sender).Name == "CopyButton_2")
                Clipboard.SetText(richTextBox2.Text);
        }

        //private void LanguageComboBox_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    Program._config.Save();
        //}

        //private void InterfaceComboBox_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    switch (InterfaceComboBox_1.SelectedItem.ToString())
        //    {
        //        case "百度":
        //            LanguageComboBox.ComboBox.DataSource = InterfaceAndLanguage.dic["百度"].Keys.ToList();
        //            break;
        //        case "有道":
        //            LanguageComboBox.ComboBox.DataSource = InterfaceAndLanguage.dic["有道"].Keys.ToList();
        //            break;
        //        case "搜狗":
        //            LanguageComboBox.ComboBox.DataSource = InterfaceAndLanguage.dic["搜狗"].Keys.ToList();
        //            break;
        //        case "腾讯":
        //            LanguageComboBox.ComboBox.DataSource = InterfaceAndLanguage.dic["腾讯"].Keys.ToList();
        //            break;
        //        default:
        //            break;
        //    }
        //    Program._config.Save();
        //}

        //置顶按钮
        private void RPButton_Click(object sender, EventArgs e)
        {
            if (this.TopMost)
            {
                this.RPButton.Image = new Bitmap(@"H:\MyOCR\MyOCR\Image\取消置顶.png");
                this.TopMost = false;
            }
            else
            {
                this.RPButton.Image = new Bitmap(@"H:\MyOCR\MyOCR\Image\置顶.png");
                this.TopMost = true;
            }
            
        }

        private void EliminateButton_Click(object sender, EventArgs e)
        {
            if (((ToolStripButton)sender).Name == "EliminateButton_1")
                richTextBox1.Clear();
            else if (((ToolStripButton)sender).Name == "EliminateButton_2")
                richTextBox2.Clear();
        }

        //作为一个中转站给其他窗体调用
        private void Transfer(Image img)
        {
            Action<Image> action = Call_OCR_API;
            Loading loading = new Loading();

            loading.Show();
            action.BeginInvoke(img, iac =>
            {
                loading.Close();
                this.notifyIcon1_MouseDoubleClick(null,null);
            },new { });
        }

        //通过线程调用API识别
        private void Call_OCR_API(Image img)
        {
            try
            {
                PictureHandle picture = PictureFactory.createPicture(Program._config._Recongnition);
                string msg = picture.IdentifyImage(img);
                richTextBox1.Text = msg;
            }
            catch (Exception ex)
            {
                richTextBox1.Text = "****************" + ex.Message + "****************";
            }
        }

        //朗读识别框
        private void RAButton_1_Click(object sender, EventArgs e)
        {
            speech.SpeakAsyncCancelAll();
            speech.SpeakAsync(richTextBox1.Text);
        }

        //朗读翻译框
        private void RAButton_2_Click(object sender, EventArgs e)
        {
            speech.SpeakAsyncCancelAll();
            speech.SpeakAsync(richTextBox2.Text);
        }
    }
}
